﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace ywxt.NewsPush.Controllers.Qualification
{
    using NHibernate;
    using NHibernate.Criterion;
    using NHibernate.Linq;
    using DB_NH;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;
    using Newtonsoft.Json;

    public class QualificationController : Controller
    {
        //
        // GET: /Qualification/

        public ActionResult Index()
        {
            return View();
        }

        #region 企业资质记录详情页面

        public ActionResult Qualification_XQ(string QId)
        {
            if (QId != null && QId != "" && QId != "0")
            {
                ViewBag.Id = QId;
            }
            return View();
        }

        #endregion

        #region 前端列表页面

        public ActionResult QualificationListView_Q()
        {
            return View();
        }

        #endregion

        #region 后台列表页面
        [Authorize(Roles = "质管部用户组")]
        public ActionResult QualificationListView()
        {
            return View();
        }

        #endregion

        #region 修改/添加的页面
        /// <summary>
        /// 显示修改/添加的页面
        /// </summary>
        /// <param name="QId">传入的ID值，如果传递的数据为空，新生成一个ID</param>
        /// <returns></returns>
        [Authorize(Roles = "质管部用户组")]
        public ActionResult Qualification(string QId)
        {
            //编辑修改
            if (QId != null && QId != "" && QId != "0")
            {
                ViewBag.Id = QId;
            }
            //新增
            else
            {
                ViewBag.Id = ywxt.Common.Common.NewID();
            }

            return View();
        }

        #endregion

        #region 添加企业资质记录

        /// <summary>
        /// 添加企业资质记录
        /// </summary>
        /// <param name="tenderOfferCfg"></param>
        /// <returns></returns>
        [Authorize(Roles = "质管部用户组")]
        public JsonResult AddQualificaton(Models.Qualification.VmQualification VmQualification)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = DB_NH.SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息
                    //遍历ViewModel VmQualification的附件列表属性VmAttachments，取出附件的id存储在是String类型的List列表ids中【便于下方验证附件时的第二个条件ids.Contains(a.ID)】
                    var ids = new List<string>();
                    foreach (var e in VmQualification.VmAttachments)
                    {
                        ids.Add(e.AId);
                    }

                    //查询附件
                    var _attachments =
                       (from a in session.Query<DB_NH.DB_Model.Attachment.Attachment>()
                        where a.IsValid == 1
                        && ids.Contains(a.Id)
                        select a)
                        .FirstOrDefault();


                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");

                    #endregion


                    #region  初始化一个企业资质表DBModel 的一个对象_qualification，并填充数据
                    var _qualification = new DB_NH.DB_Model.Qualification.Qualification()
                    {
                        //项目类型
                        Type = VmQualification.Type,

                        //项目内容
                        Content = VmQualification.Content,

                        //备注
                        Remark = VmQualification.Remark
                    };

                    #endregion


                    #region 为了把明细列表的数据填充到企业资质表的DBModel的Detail属性，而先单独处理明细列表的事务

                    //foreach循环遍历发售配置表的ViewModel（VmQualificationDetails）
                    if (VmQualification.VmQualificationDetails != null)
                    {
                        foreach (var e in VmQualification.VmQualificationDetails)
                        {
                            #region 初始化一个明细表DBModel 的一个对象_dtl，并填充数据
                            //新建一个明细表的DBModel的对象，用于存储明细表的字段信息
                            var _dtl = new DB_NH.DB_Model.Qualification.QualificationDetails()
                            {
                                //企业资质记录
                                Qualification = _qualification,

                                //资质要求
                                Details_Require = e.Details_Require,

                                //业务范围
                                Details_Range = e.Details_Range,

                                //备注
                                Details_Remark = e.Details_Remark
                            };
                            #endregion

                            //把_dtl对象的数据填充到企业资质表的DBModel对象_qualification的Details属性
                            _qualification.Details.Add(_dtl);

                            //保存配置明细表
                            session.Save(_dtl);
                        }
                    }
                    #endregion

                    //_qualification.Attachment.Add(_attachments); //添加附件信息到企业资质表里面

                    //保存企业资质表
                    session.SaveOrUpdate(_qualification);

                    //事务提交
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    //异常处理，并返回错误信息
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }
            //返回Json数据
            return Json(_returnValue);
        }

        #endregion

        #region 删除企业资质记录
        /// <summary>
        /// 删除企业资质记录
        /// </summary>
        /// <param name="qid">企业资质记录id</param>
        /// <returns></returns>
        [Authorize(Roles = "质管部用户组")]
        public JsonResult deleteQualificationData(string qid)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息

                    //获取当前登录用户名称
                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");


                    //查询企业资质记录
                    var _qualification =
                       (from p in session.QueryOver<DB_NH.DB_Model.Qualification.Qualification>()
                        where p.IsValid == 1
                        && p.Id == qid
                        select p)
                       .SingleOrDefault();

                    //核对有没有该企业资质记录
                    if (_qualification == null) throw new Exception("没有该企业资质记录，请认真核对信息");

                    #endregion


                    #region 删除企业资质记录

                    _qualification.IsValid = 0;
                    _qualification.Details.Clear();
                    // _qualification.Attachment.Clear();

                    _qualification.Remark += "(" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 由用户" + _user.user_truename_cn + "删除)";

                    session.SaveOrUpdate(_qualification);


                    #endregion

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }

            return Json(_returnValue);
        }
        #endregion

        #region 企业资质记录列表的JSON类定义
        /// <summary>
        /// 企业资质记录列表的JSON类定义
        /// </summary>
        public class JSONClassForQualification : Models.clsCommonJsonResult
        {
            public List<Models.Qualification.VmQualification> VmQualifications { get; set; }

            public JSONClassForQualification()
            {
                VmQualifications = new List<Models.Qualification.VmQualification>();
            }
        }
        #endregion

        #region 查询企业资质记录列表
        /// <summary>
        /// 根据关键字 keyword,获取企业资质记录列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public JsonResult GetQualificationList(string one_keyword, string two_keyword, string three_keyword, int pagesize, int pageindex)
        {
            var _returnValue = new JSONClassForQualification();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //资质要求不为空
                    if (three_keyword != "" || three_keyword != null)
                    {
                        var _qualification =
                   (from v in session.Query<DB_NH.DB_Model.Qualification.Qualification>()
                    from d in v.Details
                    where v.IsValid == 1
                     && v.Type.Contains(one_keyword)         //根据项目类型查询
                     && v.Content.Contains(two_keyword)      //根据项目内容查询
                     && d.IsValid == 1
                     && d.Details_Require.Contains(three_keyword) //根据资质要求查询
                    orderby v.CreateDate descending
                    select new Models.Qualification.VmQualification()
                    {
                        Qid = v.Id,
                        Type = v.Type,
                        Content = v.Content,
                        Remark = v.Remark

                    });
                        //计算查询的总记录数
                        _returnValue.RecordCount = _qualification.Count();

                        if (pagesize > 0 && pagesize > 0 && _returnValue.RecordCount > 0)
                        {
                            _returnValue.PageCount = _returnValue.RecordCount % pagesize == 0 ? _returnValue.RecordCount / pagesize : (_returnValue.RecordCount / pagesize + 1);

                            if (pageindex < 0)
                            {
                                pageindex = 0;
                            }
                            else if (pageindex >= _returnValue.PageCount)
                            {
                                pageindex = _returnValue.PageCount - 1;
                            }

                            _returnValue.PageIndex = pageindex;

                            _returnValue.VmQualifications = _qualification
                                .Skip(pageindex * pagesize)
                                .Take(pagesize)
                                .ToList();
                        }
                        else
                        {
                            _returnValue.PageCount = 1;
                            _returnValue.PageIndex = 0;

                            _returnValue.VmQualifications = _qualification
                                .ToList();
                        }

                    }

                    //资质要求为空
                    if (three_keyword == "" || three_keyword == null)
                    {
                        var _qualification =
                   (from v in session.Query<DB_NH.DB_Model.Qualification.Qualification>()
                    where v.IsValid == 1
                     && v.Type.Contains(one_keyword)         //根据项目类型查询
                     && v.Content.Contains(two_keyword)      //根据项目内容查询
                    orderby v.CreateDate descending
                    select new Models.Qualification.VmQualification()
                    {
                        Qid = v.Id,
                        Type = v.Type,
                        Content = v.Content,
                        Remark = v.Remark

                    });
                        //计算查询的总记录数
                        _returnValue.RecordCount = _qualification.Count();

                        if (pagesize > 0 && pagesize > 0 && _returnValue.RecordCount > 0)
                        {
                            _returnValue.PageCount = _returnValue.RecordCount % pagesize == 0 ? _returnValue.RecordCount / pagesize : (_returnValue.RecordCount / pagesize + 1);

                            if (pageindex < 0)
                            {
                                pageindex = 0;
                            }
                            else if (pageindex >= _returnValue.PageCount)
                            {
                                pageindex = _returnValue.PageCount - 1;
                            }

                            _returnValue.PageIndex = pageindex;

                            _returnValue.VmQualifications = _qualification
                                .Skip(pageindex * pagesize)
                                .Take(pagesize)
                                .ToList();
                        }
                        else
                        {
                            _returnValue.PageCount = 1;
                            _returnValue.PageIndex = 0;

                            _returnValue.VmQualifications = _qualification
                                .ToList();
                        }

                    }

                    transaction.Commit();
                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }
        #endregion

        #region 修改的企业资质记录的JSON类定义
        /// <summary>
        /// 企业资质记录的JSON类定义
        /// </summary>
        public class JSONClassForOneQualification : Models.clsCommonJsonResult
        {
            public Models.Qualification.VmQualification VmQualification { get; set; }

        }
        #endregion

        #region 修改企业资质记录

        /// <summary>
        /// 修改企业资质记录
        /// </summary>
        /// <param name="VmQualification"></param>
        /// <returns></returns>
        [Authorize(Roles = "质管部用户组")]
        public JsonResult updateQualification(Models.Qualification.VmQualification VmQualification)
        {
            var _returnValue = new Models.clsCommonJsonResult();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    #region 验证信息
                    //遍历ViewModel VmQualification的附件列表属性VmAttachments，取出附件的id存储在是String类型的List列表ids中【便于下方验证附件时的第二个条件ids.Contains(a.ID)】
                    var ids = new List<string>();
                    foreach (var e in VmQualification.VmAttachments)
                    {
                        ids.Add(e.AId);
                    }

                    //查询附件
                    var _attachments =
                       (from a in session.Query<DB_NH.DB_Model.Attachment.Attachment>()
                        where a.IsValid == 1
                        && ids.Contains(a.Id)
                        select a)
                        .FirstOrDefault();


                    string _this_user_name_en = ywxt.Common.Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = ywxt.Common.Common.getAuthenticatedUser(User).DisplayName;

                    //查询操作用户
                    var _user =
                        (from u in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                         where u.is_valid == 1
                         && u.user_truename_cn == _this_user_name_cn
                         && u.user_truename_en == _this_user_name_en
                         select u)
                        .FirstOrDefault();

                    //核对有没有该操作用户信息
                    if (_user == null) throw new Exception("没有该操作用户，请认真核对信息");

                    #endregion

                    #region  初始化一个企业资质表DBModel 的一个对象_qualification

                    var _qualification = (from p in session.QueryOver<DB_NH.DB_Model.Qualification.Qualification>()
                                          where p.IsValid == 1
                                          && p.Id == VmQualification.Qid
                                          select p
                              ).SingleOrDefault();

                    _qualification.Type = VmQualification.Type;
                    _qualification.Content = VmQualification.Content;
                    _qualification.Remark = VmQualification.Remark;

                    #endregion


                    #region  明细的修改

                    //逐一将原来的明细记录设置为无效记录
                    foreach (var _detail in _qualification.Details)
                    {
                        _detail.IsValid = 0;
                        session.Update(_detail);
                    }

                    //逐一循环传递的参数
                    foreach (var _new_detail in VmQualification.VmQualificationDetails)
                    {
                        if (string.IsNullOrEmpty(_new_detail.DetailId))
                        {
                            //没有明细记录ID，为新的明细记录
                            var _d = new DB_NH.DB_Model.Qualification.QualificationDetails()
                            {
                                Qualification = _qualification,
                                Details_Require = _new_detail.Details_Require,
                                Details_Range = _new_detail.Details_Range,
                                Details_Remark = _new_detail.Details_Remark
                            };
                            session.Save(_d);
                        }
                        else
                        {
                            var _isSaved = false;
                            //有明细记录ID，循环已有的明细记录
                            foreach (var _d in _qualification.Details)
                            {
                                if (_d.Id == _new_detail.DetailId)
                                {
                                    //赋值新内容到当前明细记录，并设置有效标志
                                    _d.IsValid = 1;
                                    _d.Details_Require = _new_detail.Details_Require;
                                    _d.Details_Range = _new_detail.Details_Range;
                                    _d.Details_Remark = _new_detail.Details_Remark;
                                    session.Update(_d);

                                    //退出循环
                                    _isSaved = true;
                                    break;
                                }
                            }//

                            if (!_isSaved)
                            {
                                //没有查询到明细记录，新建明细记录
                                var _e = new DB_NH.DB_Model.Qualification.QualificationDetails()
                                {
                                    Qualification = _qualification,
                                    Details_Require = _new_detail.Details_Require,
                                    Details_Range = _new_detail.Details_Range,
                                    Details_Remark = _new_detail.Details_Remark
                                };
                                session.Save(_e);
                                _qualification.Details.Add(_e);
                            }
                        }
                    }
                    #endregion

                    #region 附件的修改

                    //逐一将原来的附件记录设置为无效记录
                    /*foreach (var _a in _qualification.Attachment)
                    {
                        _a.IsValid = 0;
                        session.Update(_a);
                    }

                    //逐一循环传递的参数
                    foreach (var _a in VmQualification.VmAttachments)
                    {
                        var _isSaved = false;

                        //有附件记录ID，循环已有的附件记录
                        foreach (var _d in _qualification.Attachment)
                        {
                            if (_d.Id == _a.AId)
                            {
                                //赋值新内容到当前附件记录，并设置有效标志
                                _d.IsValid = 1;
                                session.Update(_d);

                                //退出循环
                                _isSaved = true;
                                break;
                            }
                        }

                        if (!_isSaved)
                        {
                            //没有查询到附件记录，新建附件记录
                            var _e = (from p in session.QueryOver<DB_NH.DB_Model.Attachment.Attachment>()
                                      where p.IsValid == 1
                                      && p.Id == _a.AId
                                      select p)
                           .SingleOrDefault();

                            if (_e != null)
                            {
                                _qualification.Attachment.Add(_e);
                            }

                        }
                    }*/


                    #endregion

                    //保存企业资质表
                    session.SaveOrUpdate(_qualification);

                    //事务提交
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    //异常处理，并返回错误信息
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }
            //返回Json数据
            return Json(_returnValue);
        }

        #endregion

        #region 根据id查询需要编辑的那一条企业资质记录信息
        /// <summary>
        /// 根据关键字 id,获取需要编辑的那一条企业资质记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetOneQualification(string qid)
        {
            var _returnValue = new JSONClassForOneQualification();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                //获取需要编辑的那一条企业资质记录信息
                try
                {

                    //根据id查出相应的列表
                    var _qualification =
                        (from v in session.Query<DB_NH.DB_Model.Qualification.Qualification>()
                         where v.IsValid == 1
                         && v.Id == qid
                         orderby v.CreateDate descending
                         select new Models.Qualification.VmQualification()
                         {
                             Qid = v.Id,
                             Type = v.Type,
                             Content = v.Content,
                             Remark = v.Remark,

                         }).Take(1).FirstOrDefault();

                    //查询明细表
                    var _QualificationDetail =
                    (from d in session.Query<DB_NH.DB_Model.Qualification.QualificationDetails>()
                     where d.IsValid == 1
                     && d.Qualification.Id == qid
                     orderby d.CreateDate descending
                     select new Models.Qualification.VmQualificationDetail()
                     {
                         DetailId = d.Id,
                         Qid = d.Qualification.Id,
                         Type = d.Qualification.Type,
                         Details_Require = d.Details_Require,
                         Details_Range = d.Details_Range,
                         Details_Remark = d.Details_Remark

                     }).ToList();

                    //企业资质记录里面加明细记录
                    _qualification.VmQualificationDetails = _QualificationDetail;

                    //查询附件，同时查询两个表
                    /*var _attachment =
                           (from a in session.Query<DB_NH.DB_Model.Qualification.Qualification>()
                            from b in a.Attachment
                            where a.IsValid == 1
                            && b.IsValid == 1
                            && a.Id == qid
                            select new Models.Qualification.VmAttachment()
                            {
                                AId = b.Id,
                                FileName = b.FileName

                            })
                            .ToList();*/

                    var _attachment =
                           (from a in session.Query<DB_NH.DB_Model.Attachment.Attachment>()
                            where a.IsValid == 1
                            && a.RecordId == qid
                            select new Models.Qualification.VmAttachment()
                            {
                                AId = a.Id,
                                FileName = a.FileName

                            })
                            .ToList();

                    //企业资质记录里面加附件记录
                    _qualification.VmAttachments = _attachment;

                    _returnValue.VmQualification = _qualification;

                    transaction.Commit();

                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }
        #endregion

        #region 查询明细列表的JSON类定义

        public class JSONClassForQualificationDetails : Models.clsCommonJsonResult
        {
            public List<Models.Qualification.VmQualificationDetail> VmQualificationDetails { get; set; }

            public JSONClassForQualificationDetails()
            {
                VmQualificationDetails = new List<Models.Qualification.VmQualificationDetail>();
            }
        }

        #endregion

        #region 查询明细列表
        [Authorize(Roles = "质管部用户组")]
        public JsonResult QualificationDetailList(string keyword)
        {
            var _returnValue = new JSONClassForQualificationDetails();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //根据kword查出相应的列表
                    var _qualificationDetails =
                    (from v in session.Query<DB_NH.DB_Model.Qualification.QualificationDetails>()
                     where v.IsValid == 1
                     && v.Details_Require.Contains(keyword)         //根据资质要求查询
                     && v.Qualification.Id == null                  //查询明细表中Qualification.Id 等于空的记录
                     orderby v.CreateDate descending
                     select new Models.Qualification.VmQualificationDetail()
                     {
                         DetailId = v.Id,
                         Qid = v.Qualification.Id,
                         Type = v.Qualification.Type,
                         Details_Require = v.Details_Require,
                         Details_Range = v.Details_Range,
                         Details_Remark = v.Details_Remark,

                     }).ToList();
                    _returnValue.VmQualificationDetails = _qualificationDetails;

                    transaction.Commit();

                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }

        #endregion

        #region 上传附件

        /// <summary>
        /// Ajax上传附件，操作步骤：
        /// 1、保存附件；
        /// 2、关联流程记录
        /// </summary>
        /// <param name="upfile"></param>
        /// <param name="recordid">审批流程ID</param>
        /// <param name="typename">附件类型：IMG</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "质管部用户组")]
        public ActionResult UploadAjax(string recordid, string typename, HttpPostedFileBase upfile)
        {
            var _returnValue = new Models.clsCommonJsonResult();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    Stream fileStream = upfile.InputStream;
                    string fileName = Path.GetFileName(upfile.FileName);
                    int fileLength = upfile.ContentLength;
                    byte[] fileData = new byte[fileLength];
                    fileStream.Read(fileData, 0, fileLength);

                    var _r = new DB_NH.DB_Model.Attachment.Attachment()
                    {
                        FileName = fileName,
                        TypeName = typename,
                        UploadUserName = User.Identity.Name,
                        RecordId = recordid,
                    };

                    var _r_data = new DB_NH.DB_Model.Attachment.AttachmentData()
                    {
                        Id = _r.Id,
                        AttBytes = fileData
                    };

                    session.SaveOrUpdate(_r);
                    session.SaveOrUpdate(_r_data);

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }

            return Json(_returnValue);
        }

        #endregion

        #region 下载附件

        /// <summary>
        /// 返回指定is的文件，即下载
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult downAttachment(string id)
        {
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //检查 id 
                    if (string.IsNullOrEmpty(id))
                    {
                        return Content("文件ID未指定。");
                    }

                    //获取文件名
                    var _file_name = (
                        from f in session.Query<DB_NH.DB_Model.Attachment.Attachment>()
                        where f.IsValid == 1 && f.Id == id
                        select f.FileName).Take(1).FirstOrDefault();


                    //检查文件名
                    if (string.IsNullOrEmpty(_file_name))
                    {
                        return Content("文件获取错误，名称未找到。");
                    }

                    //获取文件数据
                    var _file_data = (
                        from f in session.Query<DB_NH.DB_Model.Attachment.AttachmentData>()
                        where f.Id == id
                        select f.AttBytes).Take(1).FirstOrDefault();


                    return File(_file_data, "application/octet-stream", Url.Encode(_file_name));

                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    return Content("系统错误！错误代码：" + ex.Message);
                }
            }
        }

        #endregion

        #region 删除关联附件

        /// <summary>
        /// 按文件ID删除文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public JsonResult deleteAttachment(string id)
        {
            ywxt.NewsPush.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            #region 设置文件的可用状态为0
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //删除附件记录
                    session.Delete(session.QueryOver<DB_NH.DB_Model.Attachment.Attachment>()
                        .Where(c => c.Id == id)
                        .SingleOrDefault());
                    //删除附加数据记录
                    session.Delete(session.QueryOver<DB_NH.DB_Model.Attachment.AttachmentData>()
                        .Where(c => c.Id == id)
                        .SingleOrDefault());


                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = ex.Message;
                }
            }
            #endregion

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 附件查询列表的JSON类定义

        /// <summary>
        /// 附件查询列表的JSON类定义
        /// </summary>
        public class JSONClassForAttachments : Models.clsCommonJsonResult
        {
            public List<Models.Qualification.VmAttachment> VmAttachments { get; set; }

            public JSONClassForAttachments()
            {
                VmAttachments = new List<Models.Qualification.VmAttachment>();
            }
        }

        #endregion

        #region 查询附件列表

        /// <summary>
        /// 根据资质主类 ID ,获取附件记录列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public JsonResult AttachmentList(string id)
        {
            var _returnValue = new JSONClassForAttachments();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                //获取附件记录信息
                try
                {
                    //根据kword查出相应的列表
                    var _attachments =
                    (from v in session.Query<DB_NH.DB_Model.Attachment.Attachment>()
                     where v.IsValid == 1
                     && v.RecordId == id
                     orderby v.CreateDate descending
                     select new Models.Qualification.VmAttachment()
                     {
                         AId = v.Id,
                         FileName = v.FileName

                     }).ToList();

                    _returnValue.VmAttachments = _attachments;

                    transaction.Commit();

                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            return Json(_returnValue);
        }

        #endregion

        #region 查询获取小何返回数据列表


        public ActionResult XhList()
        {
            return View();
        }


        public class JSONClassForXH : Models.clsCommonJsonResult
        {
            public List<Models.Qualification.VmXh> VmXhs { get; set; }

            public JSONClassForXH()
            {
                VmXhs = new List<Models.Qualification.VmXh>();
            }
        }

        public ActionResult HttpClientDoGet(string type, string keyword, int? pageindex)
        {
            var _returnValue = new JSONClassForXH();
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    //待改链接
                    var uri = "http://192.168.6.65:3002/finance_qa/search";

                    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };

                    using (var httpclient = new HttpClient(handler))
                    {
                        httpclient.BaseAddress = new Uri(uri);

                        httpclient.DefaultRequestHeaders.Accept.Clear();

                        httpclient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));


                        string kw = Regex.Replace(keyword, "[ \\[ \\] \\^ \\-_*×――(^)|'$%~!@#$…&%￥—+=<>《》!！??？:：•`·、。，；,.;\"‘’“”-]", ";");

                        var _str = "?pageSize=20";

                        if (pageindex.HasValue && pageindex.Value > 0)
                        {
                            _str += "&page=" + pageindex.Value.ToString();
                        }
                        else
                        {
                            _str += "&page=0";
                        }

                        if (type == "s")
                        {
                            _str += "&type=s&nr=" + kw;
                        }
                        else
                        {
                            _str += "&nr=" + kw;
                        }

                        HttpResponseMessage response = httpclient.GetAsync(_str).Result;

                        if (response.IsSuccessStatusCode)
                        {
                            Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;

                            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

                            string retString = myStreamReader.ReadToEnd();

                            /*
                            myStreamReader.Close();

                            myResponseStream.Close();

                            //序列化
                            List<Models.Qualification.VmXh> xhList = JsonConvert.DeserializeObject<List<Models.Qualification.VmXh>>(retString);

                            _returnValue.VmXhs = xhList;
                            */
                            transaction.Commit();
                            return Content(retString);
                        }
                    }
                }
                catch (Exception _ex)
                {
                    if (transaction.IsActive) transaction.Rollback();
                    _returnValue.ISOK = false;
                    _returnValue.MESSAGE = _ex.Message;
                }
            }
            //return Json(_returnValue);

            return Json(_returnValue);
        }
        #endregion

    }
}
